package com.mydemo.sftp;

import com.mydemo.sftp.pool2.SftpClientPooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.InitializingBean;

public class SftpProviderImpl implements InitializingBean, SftpProvider {
    private SftpProperty sftpProperty;
    private GenericObjectPool<SftpClient> genericObjectPool;
    @Override
    public SftpClient getConnection() {
        try {
            return genericObjectPool.borrowObject();
        } catch (Exception e) {
            throw new RuntimeException("获取client异常");
        }
    }

    @Override
    public void releaseConnection(SftpClient sftpClient) {
        genericObjectPool.returnObject(sftpClient);
    }

    @Override
    public void afterPropertiesSet() {
        SftpClientPooledObjectFactory factory = new SftpClientPooledObjectFactory();
        factory.setSftpProperty(sftpProperty);
        genericObjectPool = new GenericObjectPool<>(factory);
    }

    public void setSftpProperty(SftpProperty sftpProperty) {
        this.sftpProperty = sftpProperty;
    }
}
